package com.the_last.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.the_last.constant.RedisKeyConstant;
import com.the_last.mapper.SysPermissionMapper;
import com.the_last.mapper.UserMapper;
import com.the_last.pojo.dto.SysPermissionDTO;
import com.the_last.pojo.po.SysPermission;
import com.the_last.service.ISysPermissionService;
import com.the_last.utils.RedisUtil;
import com.the_last.utils.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission>
        implements ISysPermissionService {
    
    private final UserMapper userMapper;
    private final RedisUtil redisUtil;
    
    private void clearPermissionCache() {
        redisUtil.delete(RedisKeyConstant.VALID_PERMISSION_IDS_KEY);
    }
    
    @Override
    public Result<Page<SysPermission>> getPermissionList(Page<SysPermission> page, SysPermissionDTO queryDTO) {
        try {
            // 使用 Mapper 层的联表查询方法
            Page<SysPermission> result = baseMapper.selectPermissionPageWithBusinessType(page, queryDTO);
            return Result.success(result);
            
        } catch (Exception e) {
            log.error("获取权限列表失败", e);
            return Result.fail("获取权限列表失败");
        }
    }
    
    @Override
    public Result<List<SysPermission>> getPermissionsByUserId(Long userId) {
        if (userId == null) {
            return Result.fail("用户ID不能为空");
        }
        
        try {
            String cacheKey = "user:permissions:" + userId;
            @SuppressWarnings("unchecked")
            List<SysPermission> cachedPermissions = redisUtil.getObject(cacheKey, List.class);
            if (cachedPermissions != null) {
                return Result.success(cachedPermissions);
            }
            
            List<SysPermission> permissions = baseMapper.selectPermissionsByUserId(userId);
            if (permissions != null) {
                redisUtil.set(cacheKey, permissions, 300); // 5分钟缓存
            }
            return Result.success(permissions);
        } catch (Exception e) {
            log.error("查询用户权限失败，userId: {}", userId, e);
            return Result.fail("查询用户权限失败");
        }
    }
    
    @Override
    public Result<List<SysPermission>> getPermissionsByRoleId(Long roleId) {
        if (roleId == null) {
            return Result.fail("角色ID不能为空");
        }
        
        try {
            String cacheKey = "role:permissions:" + roleId;
            @SuppressWarnings("unchecked")
            List<SysPermission> cachedPermissions = redisUtil.getObject(cacheKey, List.class);
            if (cachedPermissions != null) {
                return Result.success(cachedPermissions);
            }
            
            List<SysPermission> permissions = baseMapper.selectPermissionsByRoleId(roleId);
            if (permissions != null) {
                redisUtil.set(cacheKey, permissions, 300); // 5分钟缓存
            }
            return Result.success(permissions);
        } catch (Exception e) {
            log.error("查询角色权限失败，roleId: {}", roleId, e);
            return Result.fail("查询角色权限失败");
        }
    }
    
    @Override
    public Result<Void> addPermission(SysPermission permission) {
        if (permission == null) {
            return Result.fail("权限信息不能为空");
        }
        
        if (permission.getPermissionCode() == null || permission.getPermissionName() == null) {
            return Result.fail("权限编码和名称不能为空");
        }
        
        try {
            QueryWrapper<SysPermission> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("permission_code", permission.getPermissionCode())
                    .eq("deleted", 0);
            
            if (count(queryWrapper) > 0) {
                return Result.fail("权限编码已存在");
            }
            
            permission.setCreatedTime(LocalDateTime.now());
            permission.setUpdatedTime(LocalDateTime.now());
            permission.setStatus(1);
            permission.setDeleted(0);
            
            if (permission.getParentId() == null) {
                permission.setParentId(0L);
            }
            if (permission.getSortOrder() == null) {
                permission.setSortOrder(0);
            }
            save(permission);
            clearPermissionCache();
            return Result.success();
        } catch (Exception e) {
            log.error("新增权限失败", e);
            return Result.fail("新增权限失败");
        }
    }
    
    @Override
    public Result<Void> updatePermission(SysPermission permission) {
        if (permission == null || permission.getId() == null) {
            return Result.fail("权限ID不能为空");
        }
        
        try {
            SysPermission existingPermission = getById(permission.getId());
            if (existingPermission == null || existingPermission.getDeleted().equals(1)) {
                return Result.fail("权限不存在");
            }
            
            if (permission.getPermissionCode() != null &&
                    !permission.getPermissionCode().equals(existingPermission.getPermissionCode())) {
                QueryWrapper<SysPermission> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("permission_code", permission.getPermissionCode())
                        .eq("deleted", 0)
                        .ne("id", permission.getId());
                
                if (count(queryWrapper) > 0) {
                    return Result.fail("权限编码已存在");
                }
            }
            
            permission.setUpdatedTime(LocalDateTime.now());
            updateById(permission);
            return Result.success();
        } catch (Exception e) {
            log.error("更新权限失败", e);
            return Result.fail("更新权限失败");
        }
    }
    
    @Override
    public Result<Void> deletePermission(Long id) {
        if (id == null) {
            return Result.fail("权限ID不能为空");
        }
        
        try {
            SysPermission permission = getById(id);
            if (permission == null || permission.getDeleted().equals(1)) {
                return Result.fail("权限不存在");
            }
            removeById(id);
            clearPermissionCache();
            return Result.success();
        } catch (Exception e) {
            log.error("删除权限失败，id: {}", id, e);
            return Result.fail("删除权限失败");
        }
    }
    
    @Override
    public List<String> getUserPermissionCodes(Long userId) {
        if (userId == null) {
            return List.of();
        }
        
        try {
            String cacheKey = "user:permission:codes:" + userId;
            @SuppressWarnings("unchecked")
            List<String> cachedCodes = redisUtil.getObject(cacheKey, List.class);
            if (cachedCodes != null) {
                return cachedCodes;
            }
            
            List<String> permissionCodes = userMapper.selectUserPermissions(userId);
            if (permissionCodes != null) {
                redisUtil.set(cacheKey, permissionCodes, 300); // 5分钟缓存
            }
            return permissionCodes != null ? permissionCodes : List.of();
        } catch (Exception e) {
            log.error("查询用户权限代码失败，userId: {}", userId, e);
            return List.of();
        }
    }
}